﻿import com.gamemeal.physics.Point3;
import com.gamemeal.renderer.MCTransform;

/**
 * @author Colin
 */
class com.gamemeal.renderer.Cam3D{
	public var x:Number;
	public var y:Number;
	public var z:Number;
	public var rx:Number;
	public var ry:Number;
	public var rz:Number;

	public var focalLength:Number = 200;

	public var isEnable:Boolean = true;

	private function Cam3D(x,y,z,rx,ry,rz,f){
		this.x = (x==null)?0:x;
		this.y = (y==null)?0:y;
		this.z = (z==null)?0:z;
		this.rx = (rx==null)?0:rx;
		this.ry = (ry==null)?0:ry;
		this.rz = (rz==null)?0:rz;
		this.focalLength = (f==null)?200:f;
	}

	private static var ins:Cam3D;
	public static function instance(x,y,z,rx,ry,rz,f){
		if(ins == null){
			ins = new Cam3D(x,y,z,rx,ry,rz,f);
		}
		return ins;
	}

	public function setPos(x : Number, y : Number, z : Number, rx : Number, ry : Number, rz : Number) : Void {
		this.x = x;
		this.y = y;
		this.z = z;
		this.rx = rx;
		this.ry = ry;
		this.rz = rz;
	}
	
	public function project3Dto2DMCTransform(v:Point3):MCTransform{
		var mct = new MCTransform();
		var tx = v.x - x;
		var ty = v.y - y;
		var tz = v.z - z;

		var angle = Math.atan2(tz,tx);
		var radius = Math.sqrt(tx*tx + tz*tz);
		tx = Math.cos(angle + ry) * radius;
		tz = Math.sin(angle + ry) * radius;

		var scaleRatio = focalLength/(focalLength + tz);
		mct.x = tx * scaleRatio;
		mct.y = ty * scaleRatio;
		mct.xs = mct.ys = 100 * scaleRatio;
		mct.depth = Math.round(-tz);
		mct.visible = (tz>0)?true:false;
		return mct;
	}
}